package com.mapfinal.server.api.web;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.lambkit.common.util.StringUtils;
import com.mapfinal.server.api.ApiTokenManager;
import com.mapfinal.server.web.WebResult;
import com.mapfinal.server.web.WebResultConsts;

/**
 * 每个应用都有token，需要用token访问
 * @author yangyong
 *
 */
public class ApiTokenInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		// TODO Auto-generated method stub
		Controller ctl = inv.getController();
		String accessToken = ctl.getPara("tk", ctl.getPara("token", ctl.getPara("accessToken", ctl.getPara(0))));
		
		if (StringUtils.isBlank(accessToken)) {
			accessToken = ctl.getCookie("mapfinal_token", ctl.getHeader("mapfinal_token"));
		}
		// 判断accessToken是否空
        if (StringUtils.isBlank(accessToken)) {
            // 返回错误消息
        	WebResult.render(ctl, WebResultConsts.EMPTY_TOKEN, null);
            return;
        }
		if(ApiTokenManager.me().validation(accessToken)) {
			inv.invoke();
		} else {
			// accessToken 已经失效!
			WebResult.render(ctl, WebResultConsts.INVALID_TOKEN, null);
		}
	}
}
